"""
@-*- coding: utf-8 -*-
@ python: 3.12.3
@ 创建者: JacksonCode
@ 创建时间: 2025-11-06
@ 描述: 认证相关业务逻辑
"""
from werkzeug.security import check_password_hash, generate_password_hash
from app.extensions import db
from app.models.auth import Token, RefreshToken
from app.models.users import User


class AuthService:
    @staticmethod
    def authenticate_user(email, password):
        """验证用户凭据"""
        user = User.query.filter_by(email=email).first()
        if user and user.check_password(password):
            return user
        return None
    
    @staticmethod
    def create_user(email, password, username=None):
        """创建新用户"""
        # 检查邮箱是否已存在
        if User.query.filter_by(email=email).first():
            return None, "邮箱已被注册"
        
        # 创建新用户
        user = User(
            email=email,
            username=username or email.split('@')[0]
        )
        
        # 设置密码
        user.set_password(password)
        
        db.session.add(user)
        db.session.commit()
        
        return user, None
    
    @staticmethod
    def get_user_by_id(user_id):
        """根据ID获取用户"""
        return User.query.get(user_id)
    
    @staticmethod
    def update_user_password(user_id, new_password):
        """更新用户密码"""
        user = User.query.get(user_id)
        if user:
            user.set_password(new_password)
            db.session.commit()
            return True
        return False
    
    @staticmethod
    def create_token(user_id, expires_in=3600):
        """创建访问令牌"""
        token = Token(user_id=user_id, expires_in=expires_in)
        db.session.add(token)
        db.session.commit()
        return token
    
    @staticmethod
    def create_refresh_token(user_id):
        """创建刷新令牌"""
        refresh_token = RefreshToken(user_id=user_id)
        db.session.add(refresh_token)
        db.session.commit()
        return refresh_token
    
    @staticmethod
    def verify_token(token_value):
        """验证令牌"""
        token = Token.query.filter_by(token=token_value, revoked=False).first()
        if token and not token.is_expired():
            return token.user_id
        return None
    
    @staticmethod
    def revoke_token(token_value):
        """撤销令牌"""
        token = Token.query.filter_by(token=token_value).first()
        if token:
            token.revoked = True
            db.session.commit()
            return True
        return False